<template>
	<div ref="vrContainer" id="vr-container"></div>
	<!-- <canvas ref="canvas" style="width: 100%; height: 100%;"></canvas> -->
</template>

<script setup>
	import {
		onMounted,
		onBeforeUnmount,
		ref
	} from 'vue';
	import * as THREE from 'three';

	const vrContainer = ref(null);
	const canvas = ref(null)
	let scene, camera, renderer;

	onMounted(() => {
		initThree();
	});

	onBeforeUnmount(() => {
		if (renderer) {
			renderer.dispose();
		}
	});
	function initThree() {
		// 创建场景
		scene = new THREE.Scene();

		// 创建相机
		camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

		// 创建渲染器
		renderer = new THREE.WebGLRenderer({
			antialias: true
		});
		
		renderer.setSize(window.innerWidth, window.innerHeight);
		vrContainer.value.appendChild(renderer.domElement);

		// 创建一个球体模型
		const geometry = new THREE.SphereGeometry(200, 32, 32); // 半径大一些以保证相机在内部
		
		
		// 加载器
		const textureLoader = new THREE.TextureLoader();

		textureLoader.load('/static/tick2.jpg', (texture) => {
			console.log(texture)
			//生成一个材质
			const material = new THREE.MeshBasicMaterial({
				map: texture,
				side: THREE.DoubleSide
			});
			//把球体模型和材质关联起来
			const sphere = new THREE.Mesh(geometry, material);
			//把关联好的模型添加到场景中
			scene.add(sphere);
		});
		// 加载全景图像作为纹理
		// const texture = textureLoader.load('/static/tick2.jpg'); // 替换为你的图片路径
		// const material = new THREE.MeshBasicMaterial({
		// 	color: 0x00ff00
		// });
		// const sphere = new THREE.Mesh(geometry, material);
		// scene.add(sphere);

		// 动画循环
		// animate();
		camera.position.set(0, 0, 0); // 适当调整相机位置以便于观看
		animate()
		// renderer.setAnimationLoop(animate);
		// 处理窗口大小变化
		window.addEventListener('resize', onWindowResize);
		// window.addEventListener('touchmove', () => {
			window.addEventListener('touchmove', e => {
				console.log('aaa')
				updateCamera(e, camera)
			})
		// })
		
	}

	function updateCamera(event, camera) {
		event.preventDefault();
		
		      // 获取触摸点的位置
		      const touchX = event.touches[0].clientX;
		      const touchY = event.touches[0].clientY;
		
		      // 将触摸坐标转换为标准化设备坐标
		      const mouseX = (touchX / window.innerWidth) * 2;
		      const mouseY = -(touchY / window.innerHeight) * 2;
		
		      // 更新相机的旋转
		      camera.rotation.y = mouseX * Math.PI;  // 根据触摸移动更新水平旋转
		      camera.rotation.x = mouseY * Math.PI; // 根据触摸移动更新垂直旋转
	}

	function animate() {
		console.log(1111)
		requestAnimationFrame(animate);
		renderer.render(scene, camera);
	}

	function onWindowResize() {
		camera.aspect = window.innerWidth / window.innerHeight;
		camera.updateProjectionMatrix();
		renderer.setSize(window.innerWidth, window.innerHeight);
	}
</script>

<style scoped>
	#vr-container {
		width: 100%;
		height: 100vh;
		overflow: hidden;
	}
</style>